package com.molichuxing.framework.utils;

/*import Decoder.BASE64Decoder;
import Decoder.BASE64Encoder;*/



import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


public class AesUtil {
    /*
     * 加密用的Key 可以用26个字母和数字组成 此处使用AES-128-CBC加密模式，key需要为16位。
     */
    private static String sKey = "com.molichuxing.terminal";//key，加密的key
    private static String ivParameter = "1201230125462244";//偏移量,4*4矩阵
    private static AesUtil instance = null;

    private AesUtil() {

    }

    public static AesUtil getInstance() {
        if (instance == null) {
            instance = new AesUtil();
        }
        return instance;
    }

    /**
     * 加密
     *
     * @param sSrc 要加密的内容
     * @return 加密后的字符串
     * @throws Exception
     */
    public static String encrypt(String sSrc) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] raw = getKey(sKey).getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());// 使用CBC模式，需要一个向量iv，可增加加密算法的强度
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
        return new BASE64Encoder().encode(encrypted).replaceAll("\r|\n", "");// 此处使用BASE64做转码。
    }

    /**
     * 解密
     *
     * @param sSrc 要解密的内容
     * @return 解密后的字符串
     * @throws Exception
     */
    /*public String decrypt(String sSrc) throws Exception {
        try {
            byte[] raw = getKey(AppUtil.getCPUSerial()).getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);// 先用base64解密
            byte[] original = cipher.doFinal(encrypted1);
            return new String(original, "utf-8");
        } catch (Exception ex) {
            return null;
        }
    }*/
    /**
     * 解密
     *
     * @param sSrc 要解密的内容
     * @return 解密后的字符串
     * @throws Exception
     */
    public static String decrypt(String sSrc,String key) throws Exception {
        try {
            byte[] raw = getKey(key).getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);// 先用base64解密
            byte[] original = cipher.doFinal(encrypted1);
            return new String(original, "utf-8");
        } catch (Exception ex) {
            return null;
        }
    }



    /**
     * 获取加密key
     *
     * @param sKey
     * @return
     */
    public static String getKey(String sKey) {
        StringBuffer sbKey = new StringBuffer();
        if (sKey == null) {
            sbKey.append("0000000000000000");
        } else {
            sbKey.append(sKey);
            // 长度不足16后补0
            if (sbKey.length() <= 16) {
                while (sbKey.length() < 16) {
                    sbKey.append("0");
                }
                // 大于16截取
            } else if (sbKey.length() > 16) {
                return sbKey.substring(0, 16);
            }
        }
        return sbKey.toString();
    }

    public static void main(String[] args) {
        try {
            String str="54lBYTNNZ7vFDARO933CiN4193A+LDzjvrxBG015GXUOGM9lFtg2P92WIhzCj1R+g4QtwDKWXX244RxbiFLeqNaPkQDMSFVZFtPRC461bOQ=";
            String strDate = decrypt(str,sKey);
            System.out.println(strDate);

            String str222="{\"cpu\":\"66311f459668a4d2\",\"currentTime\":\"1548065132849\",\"operate\":\"heart\"}";
            String encrypt = encrypt(str222);
            System.out.println(encrypt);

            String strDate44 = decrypt(encrypt,sKey);
            System.out.println(strDate44);

            String str2="7QsNRDFODaNVOlCWOIJQX2J8ktuFyWKSURHLLSAdrhVCqhJceUX4FlqPdwuH2lIvNh9lKnkdKKmi+X8TGOe4ZeFJ0G3+iNi0udlS178o07DNHaXmPa+aoE4ljQHmiZZyqhVT66Y8qUsK1ol+0pyJb/F346gvavARYmFiHzUwfT15XI8IkaT+WP54wL+fd4ZBr6ootEMEFOBowjAxhWedW7HDZ1qQxXpz9XuNquVCn/R4Rqdz0bqNqpL605e5rNj5GCuDYceF0UL+rC8TO0uTpaijxGibFuEOwFDdTDxNBj2jMKj1Uf0Uv+5eZyN5aiVYFJstC/lwqBilSHCiYL9fc8ld4sXBu8Q7G3ylt68jsoSFlUT/l2fczamcLKBVahUrTtL/XOjbkuwq2QhQ1I2jCRWoXtVf1vH8/fajVinvy6puLNLAVhFET9El2teoIBT/F2IyvBahjQtg/E3vyFrzKKJ/4njvbZoc8k59OSRfqZ9X2oIcQiEkjdUcroFcBlhnnhLgev3SF+apDfrsHqHLIL8U3+Bq6ipXrlAR2Jv0awW54WQW/qqrh/dPCTva6dYsKjQy+aWGZQrY8B4J1BVqTUN6sbwZGZ4QAwcQfiOp9vW1sP74gydR/zMWMy5wNvz7JEVtG2ZtWzWNVP/xr7gVL28WUj4cETKXRGa7PueFuJj4qHXFwCtaXU/c5finXCxL7Fgp5aD2vYJ3IOaXqqY7g+yXOrQsGjA2s6GXxmQARMGbeC1mjIhOi1xUZvT32QkP855MqJRNRmQ2caHkKdn3ef8D9ZJrEheFVRsXdp5lrArq51nYMmbUK/7cSjbdWCATmV1VOQcUZY4dO0nC5ot4wXTvQVR+YpakR3srXYUFSuKi+oAJyl9Qf+2dTttwOh6/BZmLftwLRZukX0zJVHvfsh4veuqlkFFULUSimhsR2O/SsJDvhaQy419rmtKLoUInfLI3ZWBe4DkN1eEgUM7l1I/61s7adhtuaw0NwdLYOMeJwezwgmhwNVMyLq41StgOS56W7ujnWpG2xwBoukw7PHib+3ZAg2iZoCn5G5KqERv6j9jdebA9Tf3RvDNNGxmMtcxQgLh91RwXGQkGBBq6Hg==";
            String strDate2 = decrypt(str2,sKey);
            System.out.println(strDate2);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
